package com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.singletask;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.rule.common.DataRuleResult;
import com.iwhalecloud.bss.kite.client.dto.rule.common.DataRuleResultObj;
import com.iwhalecloud.bss.kite.client.dto.rule.common.RejectPromptMessage;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.rule.check.ICheckService;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.account.ILocalAccountService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IAttachmentService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.api.scene.ISceneCommitService;
import com.iwhalecloud.bss.kite.cucc.client.dto.account.CustAccountDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.account.QryCustAccountReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.req.QryStockAttachMentUrlReqDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.rsp.QryStockAttachMentUrlRspDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.webService.CustContractRsp;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.StrTools;
import com.iwhalecloud.bss.kite.cucc.manager.inst.CuccKiteOfferInstAcct;
import com.iwhalecloud.bss.kite.cucc.manager.scene.service.operate.LocalOperateOfferInstContractRelService;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalQuerySeqHelper;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.KiteBatchAcceptDetailService;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.StatusConst;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstContract;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.rul.core.client.dto.common.RuleCommonParam;
import com.ztesoft.zsmart.core.log.ZSmartLogger;

/**
 * Created by huanghaosheng on 2021/5/11 16:18
 */
public class AddGroupSingleTask extends AbstractSingleTask {
    private final ZSmartLogger logger = ZSmartLogger.getLogger(AddGroupSingleTask.class);

    public AddGroupSingleTask(KiteBatchAcceptDetailDTO kiteBatchAcceptDetail) {
        super(kiteBatchAcceptDetail);
    }

    @Override
    protected void handle() {
        ICheckService checkService = SpringUtil.getBean(ICheckService.class);
        ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
        KiteBatchAcceptDetailService kiteBatchAcceptDetailService = SpringUtil
            .getBean(KiteBatchAcceptDetailService.class);
        String groupId = "";
        String contractCode = "";
        String accountId = "";
        String groupName = "";

        String attrJson = kiteBatchAcceptDetail.getAttrJson();
        if (KiteStringUtils.isEmpty(attrJson)) {
            return;
        }
        List<KiteAttr> kiteAttrs = JSONObject.parseArray(attrJson, KiteAttr.class);
        for (KiteAttr kiteAttr : kiteAttrs) {
            if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "groupId")) {
                groupId = kiteAttr.getValue();
            }
            else if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "contractCode")) {
                contractCode = kiteAttr.getValue();
            }
            else if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "accountId")) {
                accountId = kiteAttr.getValue();
            }
            else if (KiteStringUtils.isEqual(kiteAttr.getFieldName(), "groupName")) {
                groupName = kiteAttr.getValue();
            }
        }

        if (!checkRequiredParameters(groupId, contractCode, groupName, accountId)) {
            return;
        }
        try {
            if (KiteStringUtils.isNotEmpty(groupId)) {
                KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
                kiteCustomerInfoReq.setGroupId(groupId);
                kiteCustomerInfoReq.setProvinceCode(kiteBatchAcceptDetail.getProvinceId());
                kiteCustomerInfoReq.setEparchyCode(kiteBatchAcceptDetail.getLanId());
                kiteCustomerInfoReq.setPageNum(1);
                kiteCustomerInfoReq.setPageSize(1);
                PageInfo<CuccCustInfoDTO> page = custReceptionService.customerListQueryNew(kiteCustomerInfoReq);
                if (page.getList().size() == 0) {
                    kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD,
                        kiteBatchAcceptDetail.getDetailId(), "当前客户不存在!", kiteBatchAcceptDetail.getBatchId());
                    return;
                }

                groupId = page.getList().get(0).getCustId();

                RuleCommonParam ruleCommonParam = new RuleCommonParam();
                ruleCommonParam.setLanId(kiteBatchAcceptDetail.getLanId());
                ruleCommonParam.setOrgId(kiteBatchAcceptDetail.getCreateOrgId());
                ruleCommonParam.setSysUserId(Long.toString(kiteBatchAcceptDetail.getCreateStaff()));
                ruleCommonParam.setCustId(groupId);
                DataRuleResult dataRuleResult = checkService.checkSelectCustData(groupId, ruleCommonParam);
                logger.info("正在校验group_id>>>>>>>>>>>>>>----------------" + groupId);
                if (parsingDataRuleStatus(dataRuleResult)) {
                    logger.info("校验成功--group_id>>>>>>>>>>>>>>----------------" + groupId);
                    String checkResult = KiteStringUtils.isNotEmpty(dataRuleResult.getResultMsg()) ?
                        dataRuleResult.getResultMsg() :
                        "校验成功";
                    kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailCheckStatus(StatusConst.SUCCESS_STATUSCD,
                        kiteBatchAcceptDetail.getDetailId(), checkResult, kiteBatchAcceptDetail.getBatchId());
                    //进行转单操作,并更新成功校验结果
                    commitCollectionGroup(groupId, groupName, contractCode, accountId);
                }
                else {
                    // 更新失败校验结果
                    String resultMsg = parsingDataRuleMessage(dataRuleResult);
                    logger.info("校验失败--group_id>>>>>>>>>>>>>>----------------" + groupId);
                    //TODO 规则解析有问题,暂时这么处理
                    kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD,
                        kiteBatchAcceptDetail.getDetailId(), "当前客户不存在!", kiteBatchAcceptDetail.getBatchId());
                }
            }
        }
        catch (BssException e) {
            // 更新失败校验结果
            logger.info("校验失败--group_id>>>>>>>>>>>>>>----------------" + groupId);
            //TODO 规则解析有问题,暂时这么处理
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "当前客户不存在!", kiteBatchAcceptDetail.getBatchId());
        }
    }

    /**
     * 校验必填参数
     *
     * @param groupId
     * @param contractCode
     * @param groupName
     */
    private boolean checkRequiredParameters(String groupId, String contractCode, String groupName, String accountId) {
        KiteBatchAcceptDetailService kiteBatchAcceptDetailService = SpringUtil
            .getBean(KiteBatchAcceptDetailService.class);
        if (KiteStringUtils.isEmpty(groupId)) {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "集团客户编号为空！", kiteBatchAcceptDetail.getBatchId());
            return false;
        }
        if (KiteStringUtils.isEmpty(contractCode)) {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "合同编号为空！", kiteBatchAcceptDetail.getBatchId());
            return false;
        }
        if (KiteStringUtils.isEmpty(groupName)) {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "收入归集集团名称为空！", kiteBatchAcceptDetail.getBatchId());
            return false;
        }
        if (KiteStringUtils.isNotEmpty(accountId) && !KiteStringUtils.isNum(accountId)) {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "账户标识不正确！", kiteBatchAcceptDetail.getBatchId());
            return false;
        }
        if (KiteStringUtils.isNotEmpty(groupId) && !KiteStringUtils.isNumOrChar(groupId)) {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "集团客户编号不正确！", kiteBatchAcceptDetail.getBatchId());
            return false;
        }
        return true;
    }

    /**
     * 解析DataRule，获取校验结果标识
     *
     * @param dataRuleResult
     * @return
     */
    private boolean parsingDataRuleStatus(DataRuleResult dataRuleResult) {
        if (KiteObjectUtils.isEmpty(dataRuleResult) && KiteObjectUtils.isEmpty(dataRuleResult.getResultObject())) {
            return false;
        }
        DataRuleResultObj dataRuleResultObj = dataRuleResult.getResultObject();
        //校验成功
        if (KiteStringUtils.isEqual("0000", dataRuleResult.getResultCode()) || dataRuleResultObj.getCheckFlag()) {
            return true;
        }
        return false;
    }

    /**
     * 提交收入归集校验通过的数据
     *
     * @param groupId
     */
    private void commitCollectionGroup(String groupId, String groupName, String contractCode, String accountId) {
        ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        querySceneInstService.getSceneInst(kiteBatchAcceptDetail.getSceneInstId(),
            kiteBatchAcceptDetail.getCustId());
        ISceneCommitService sceneCommitService = SpringUtil.getBean(ISceneCommitService.class);
        KiteBatchAcceptDetailService kiteBatchAcceptDetailService = SpringUtil
            .getBean(KiteBatchAcceptDetailService.class);

        String sceneInstId = kiteBatchAcceptDetail.getSceneInstId();
        String checkMsg = "";
        String checkStatus = "";
        try {
            Boolean checkAccountModule = false;
            Boolean checkContractModule = false;
            if (KiteStringUtils.isNotEmpty(sceneInstId) && KiteStringUtils.isNotEmpty(groupId)) {
                CuccContextCustDTO contextCust = new CuccContextCustDTO();
                KiteOfferInst kiteOfferInst = querySceneInstService.getMainOfferInst(sceneInstId);
                CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(groupId);
                if (Objects.nonNull(cuccCustInfoDTO) && Objects.nonNull(kiteOfferInst)) {
                    KiteBeanUtils.copyProperties(cuccCustInfoDTO, contextCust);
                    contextCust.setProvinceCode(cuccCustInfoDTO.getProvinceCode());
                    contextCust.setCustName(cuccCustInfoDTO.getCustName());
                    contextCust.setLanId(cuccCustInfoDTO.getCityCode());
                    contextCust.setRegionId(cuccCustInfoDTO.getBcityCode());
                    contextCust.setCustType(cuccCustInfoDTO.getCustClassType());
                    contextCust.setBbssCustId(cuccCustInfoDTO.getBbssCustId());
                    contextCust.setCbssId(cuccCustInfoDTO.getCustId());
                    contextCust.setAttrs(cuccCustInfoDTO.getAttrs());
                    // 如果是创建导入，才补充处理合同信息和付费关系
                    if (!KiteObjectUtils.isEmpty(kiteOfferInst) && KiteStringUtils
                        .isNotEmpty(kiteOfferInst.getOfferInstId())) {
                        if (!dealContract(groupId, contractCode, kiteOfferInst.getOfferInstId())) {
                            checkMsg = "本客户下无此合同编号!";
                            checkStatus = StatusConst.FAIL_STATUSCD;
                            return;
                        }  //处理合同信息
                        if (!dealAccount(groupId, accountId, contextCust, kiteOfferInst)) {
                            return;
                        } //处理付费关系
                    }
                    dealCommonValue(groupName, contextCust);
                    DataResult result = sceneCommitService
                        .commitScene(sceneInstId, Long.toString(kiteBatchAcceptDetail.getCreateStaff()),
                            kiteBatchAcceptDetail.getCreateOrgId(), contextCust, checkAccountModule, checkContractModule);
                    TimeUnit.MILLISECONDS.sleep(300); //调完转单逻辑,睡眠300毫秒，释放CPU资源
                    if (!KiteObjectUtils.isEmpty(result) && !KiteObjectUtils.isEmpty(result.getResultObject())) {
                        logger.info("转单成功group_id>>>>>>>>>>>>>>----------------" + groupId);
                        StringBuilder commitResultStr = new StringBuilder();
                        commitResultStr.append("提交成功,订单编号：").append(result.getResultObject());
                        kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailStatus(StatusConst.SUCCESS_STATUSCD,
                            kiteBatchAcceptDetail.getDetailId(), commitResultStr.toString(), kiteBatchAcceptDetail.getBatchId());
                    }
                    else {
                        logger.info("转单失败group_id>>>>>>>>>>>>>>----------------" + groupId);
                        kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailStatus(StatusConst.FAIL_STATUSCD,
                            kiteBatchAcceptDetail.getDetailId(),
                            KiteStringUtils.isNotEmpty(result.getResultDetail()) ? result.getResultDetail() : "转单失败",
                            kiteBatchAcceptDetail.getBatchId());
                    }
                }
                else {
                    logger.info("转单失败group_id>>>>>>>>>>>>>>----------------" + groupId);
                    kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD,
                        kiteBatchAcceptDetail.getDetailId(), "获取不到当前客户", kiteBatchAcceptDetail.getBatchId());
                }
            }
        }
        catch (Exception e) {
//            e.printStackTrace();
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    KiteStringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "转单失败",
                    kiteBatchAcceptDetail.getBatchId());
            logger.info("转单失败group_id>>>>>>>>>>>>>>----------------" + groupId);
        }
        finally {
            if (KiteStringUtils.isNotEmpty(checkStatus) && KiteStringUtils.isNotEmpty(checkMsg)) {
                kiteBatchAcceptDetailService
                    .updateKiteBatchAcceptDetailCheckStatus(checkStatus, kiteBatchAcceptDetail.getDetailId(), checkMsg,
                        kiteBatchAcceptDetail.getBatchId());
            }
        }
    }

    private void dealCommonValue(String groupName, CuccContextCustDTO contextCust) {
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        String serialNumber = "";
        Map<String, String> inParam = new HashMap<>();
        inParam.put("SEQ_TYPE", "SERIAL_NUMBER");
        inParam.put("SYS_TYPE", "1");
        inParam.put("SYS_SOURCE", "");
        serialNumber = LocalQuerySeqHelper
            .getSeqBySeqType(inParam, kiteBatchAcceptDetail.getSceneInstId(), contextCust);
        operateSceneInstService
            .putExtParameter(kiteBatchAcceptDetail.getSceneInstId(), "business_number", serialNumber);
        operateSceneInstService
            .setCommonAttrValue(kiteBatchAcceptDetail.getSceneInstId(), "business_number", serialNumber,
                serialNumber);
        operateSceneInstService.setCommonAttrValue(kiteBatchAcceptDetail.getSceneInstId(), "PRIMARY_USER_NAME",
            contextCust.getCustName() + "收入归集集团", contextCust.getCustName() + "收入归集集团");
        operateSceneInstService
            .setCommonAttrValue(kiteBatchAcceptDetail.getSceneInstId(), "group_user_name", groupName,
                groupName);
        String provinceCode = KiteStringUtils.isEmpty(contextCust.getProvinceCode()) ?
            "" :
            contextCust.getProvinceCode();
        String eparchyCode = KiteStringUtils.isEmpty(contextCust.getEparchyCode()) ? "" : contextCust.getEparchyCode();
        String cityCode = KiteStringUtils.isEmpty(contextCust.getBcityCode()) ? "" : contextCust.getBcityCode();

        operateSceneInstService.setCommonAttrValue(kiteBatchAcceptDetail.getSceneInstId(), "user_location",
            provinceCode + "," + eparchyCode + "," + cityCode, provinceCode + "," + eparchyCode + "," + cityCode);
    }

    /**
     * 处理付费关系
     *
     * @param groupId
     * @param accountId
     * @param contextCust
     * @param offerInst
     */
    private boolean dealAccount(String groupId, String accountId, CuccContextCustDTO contextCust,
        KiteOfferInst offerInst) {
        KiteBatchAcceptDetailService kiteBatchAcceptDetailService = SpringUtil
            .getBean(KiteBatchAcceptDetailService.class);
        boolean flag = false;
        ILocalAccountService accountService = SpringUtil.getBean(ILocalAccountService.class);
        // 1、明细表的account_id存在情况下,查询账户信息。
        PageInfo<QryCustAccountReq> list = new PageInfo<QryCustAccountReq>();
        QryCustAccountReq qryCustAccountReq = null;
        if (KiteStringUtils.isNotEmpty(accountId)) {
            list = accountService
                .listCustAccountInfo(groupId, "", "", accountId, "", "", "", contextCust.getProvinceCode(),
                    ContextUtil.getLoginInfo().getUserInfo().getPostLanId(), null, 1, 5);
            dealAccountSpecAttr(list);
            if (KiteListUtils.isNotEmpty(list.getList())) {
                qryCustAccountReq = list.getList().stream().filter(
                    qryCustAccount -> !KiteObjectUtils.isEmpty(qryCustAccount.getCustAccount()) && KiteStringUtils
                        .isNotEmpty(qryCustAccount.getCustAccount().getCbssAccountCode())).findFirst()
                    .orElse(null); //筛选出有cbss账户标识的账户
            }
            else {
                kiteBatchAcceptDetailService.updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD,
                    kiteBatchAcceptDetail.getDetailId(), "本客户下无此账户！", kiteBatchAcceptDetail.getBatchId());
            }
        }
        else { // 如果账户ID为空，查客户下有CBSS账户标识的账户关联
            list = accountService.listCustAccountInfo(groupId, "", "", "", "", "", "", contextCust.getProvinceCode(),
                ContextUtil.getLoginInfo().getUserInfo().getPostLanId(), null, 1, 5);
            dealAccountSpecAttr(list);
            qryCustAccountReq = list.getList().stream().filter(
                qryCustAccount -> !KiteObjectUtils.isEmpty(qryCustAccount.getCustAccount()) && KiteStringUtils
                    .isNotEmpty(qryCustAccount.getCustAccount().getCbssAccountCode())).findFirst()
                .orElse(null); //筛选出有cbss账户标识的账户
        }
        if (KiteObjectUtils.isEmpty(qryCustAccountReq) || KiteObjectUtils.isEmpty(qryCustAccountReq.getCustAccount())) {
            kiteBatchAcceptDetailService
                .updateKiteBatchAcceptDetailCheckStatus(StatusConst.FAIL_STATUSCD, kiteBatchAcceptDetail.getDetailId(),
                    "本客户下无有CBSS账户标识账户！", kiteBatchAcceptDetail.getBatchId());
        }
        else {
            commitAccount(groupId, offerInst, qryCustAccountReq);
            flag = true;
        }
        return flag;
    }

    /**
     * 提交付费关系
     *
     * @param groupId
     * @param offerInst
     * @param qryCustAccountReq
     */
    private void commitAccount(String groupId, KiteOfferInst offerInst, QryCustAccountReq qryCustAccountReq) {
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        logger.info("开始查询账户信息:group_id>>>>>>>>>>>>>>" + groupId);
        CustAccountDTO custAccountDTO = qryCustAccountReq.getCustAccount();
        CuccKiteOfferInstAcct offerInstAcct = new CuccKiteOfferInstAcct();
        KiteBeanUtils.copyProperties(custAccountDTO, offerInstAcct);
        dealOfferInstAcct(custAccountDTO, offerInstAcct, offerInst);
        if (KiteStringUtils.equals(offerInstAcct.getActionType().name(), ActionType.D.name())) {
            operateSceneInstService.deleteOfferInstAcct(kiteBatchAcceptDetail.getSceneInstId(),
                offerInstAcct.getOfferObjInstRelId());
        }
        else {
            List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService.listOfferInstAccts(groupId, offerInst.getOfferInstId());
            if (KiteListUtils.isEmpty(offerInstAcctRels)) {
                String custId = querySceneInstService.getSceneInst(kiteBatchAcceptDetail.getSceneInstId()).getCustId();
                offerInstAcctRels = querySceneInstService
                    .listOfferInstAccts(custId, offerInst.getOfferInstId());
            }
            if (!KiteListUtils.isEmpty(offerInstAcctRels)) {
                // 删除，否侧封装付费关系有问题
                offerInstAcctRels.forEach(_acct -> {
                    operateSceneInstService.deleteOfferInstAcct(kiteBatchAcceptDetail.getSceneInstId(),
                        _acct.getOfferObjInstRelId());
                });
            }
            String offerInstId = offerInstAcct.getOfferInstId();
            offerInstAcct.setInstType(InstType.OFFER_INST_ACCT);
            // 没有账户明细关系，明细ID传销售品id
            String offerId = "";
            if (!KiteObjectUtils.isEmpty(offerInst) && KiteStringUtils.isNotEmpty(offerInst.getOfferId())) {
                offerId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getOfferId).orElse("");
            }
            logger.info("开始处理付费关系:group_id>>>>>>>>>>>>>>" + groupId + "----账户标识AcctId>>>>>>>>>>>>>>" + offerInstAcct
                .getAcctId());
            operateSceneInstService
                .addOfferInstAcct(kiteBatchAcceptDetail.getSceneInstId(), offerInstAcct, offerInstId,
                    RelType.OFFER_OBJ_REL_TYPE_170000, ActionType.A, KeyConsts.OFFER_ACCOUNT_ROLE, offerId);

        }
    }

    private void dealOfferInstAcct(CustAccountDTO custAccountDTO, CuccKiteOfferInstAcct offerInstAcct,
        KiteOfferInst offerInst) {
        offerInstAcct.setAcctId(Long.toString(custAccountDTO.getAcctId()));
        offerInstAcct.setAcctItemId("0"); //TODO
        offerInstAcct.setAcctName(custAccountDTO.getPayName());
        offerInstAcct.setActionType(ActionType.A);
        offerInstAcct.setCustId(Long.toString(custAccountDTO.getCustId()));
        offerInstAcct.setIsDefault("1");
        offerInstAcct.setOfferInstId(offerInst.getOfferInstId());
        offerInstAcct.setOfferName(offerInst.getOfferName());
        offerInstAcct.setPayLimit(custAccountDTO.getPayModeCode());
        offerInstAcct.setPayWay(custAccountDTO.getPayModeCode());
        String currentDate = DateFormatUtils.getFormatedDate();
        offerInstAcct.setStartDate(DateFormatUtils.getFirstDayInMonth(currentDate, "yyyy-MM"));
        offerInstAcct.setOpenDateFormat(offerInstAcct.getOpenDateFormat());
        offerInstAcct.setEndDate("2099-12");
    }

    private void dealAccountSpecAttr(PageInfo<QryCustAccountReq> list) {
        if (KiteListUtils.isNotEmpty(list.getList())) {
            list.getList().stream().forEach(account -> {
                if (Objects.nonNull(account.getCustAccount().getOpenDate())) {
                    Long time = account.getCustAccount().getOpenDate().getTime();
                    account.getCustAccount().setOpenDateFormat(DateUtils.formatTime(time));
                }
                String provinceName = LocalAttrHelper.getRegionName(account.getCustAccount().getProvinceCode());
                String eparchyName = LocalAttrHelper.getRegionName(account.getCustAccount().getEparchyCode());
                account.getCustAccount()
                    .setAccountLocation(KiteStringUtils.join(provinceName, Symbols.HYPHEN, eparchyName));
            });
        }
    }

    /**
     * 处理合同信息
     *
     * @param groupId
     * @param contractCode
     * @param offerInstId
     */
    private boolean dealContract(String groupId, String contractCode, String offerInstId) {
        boolean flag = false;
        IInfServiceBus infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(kiteBatchAcceptDetail.getSceneInstId());
        String cateId = CuccPosServiceUtils.getCateId(kiteSceneInst.getSceneInstId(), kiteSceneInst.getCustId());
        List<CustContractRsp> contractInfoList = infServiceBus
            .listContractInfo(groupId, contractCode, "", "01", kiteBatchAcceptDetail.getProvinceId(), 1, 10,cateId);
        if (KiteListUtils.isNotEmpty(contractInfoList)) {
            logger.info("开始处理合同信息:group_id>>>>>>>>>>>>>>" + groupId + "当前主套餐OfferInstId:" + offerInstId);
            contractInfoList.stream().forEach(contractInfo -> {
                commitContract(kiteBatchAcceptDetail.getSceneInstId(), offerInstId,
                    contractInfo.getContractId(), contractInfo.getContractNo(), contractInfo.getContractName(),
                    contractInfo.getAccessoryId(), "", contractInfo.getContractType());
            });
            flag = true;
            logger.info("处理合同信息结束:group_id>>>>>>>>>>>>>>" + groupId + "共" + contractInfoList.size() + "条合同");
        }
        else {
            logger.info("查询不到合同信息:group_id>>>>>>>>>>>>>>" + groupId + "当前主套餐OfferInstId:" + offerInstId);
        }
        return flag;
    }

    /**
     * 处理OfferInstContractRel关系
     *
     * @param sceneInstId
     * @param offerInstId
     * @param contractId
     * @param contractNo
     * @param contractName
     * @param accessoryId
     * @param stockFileUrl
     * @param contractType
     */
    private void commitContract(String sceneInstId, String offerInstId, String contractId, String contractNo,
        String contractName, String accessoryId, String stockFileUrl, String contractType) {
        LocalOperateOfferInstContractRelService operateOfferInstContractRelService = SpringUtil
            .getBean(LocalOperateOfferInstContractRelService.class);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        List<String> offerInstIdList = KiteListUtils.strToList(",", offerInstId);
        QryStockAttachMentUrlReqDTO qryStockAttachMentUrlReq = new QryStockAttachMentUrlReqDTO();
        qryStockAttachMentUrlReq.setProvinceCode(kiteBatchAcceptDetail.getProvinceId());
        qryStockAttachMentUrlReq.setEsbFileName(stockFileUrl);
        String realPath = StrTools.isEmpty(stockFileUrl) ? accessoryId : getUrl(qryStockAttachMentUrlReq);
        KiteSceneInst kiteSceneInst = querySceneInstService
            .getSceneInst(kiteBatchAcceptDetail.getSceneInstId());

        offerInstIdList.stream().forEach(t -> {
            if (KiteStringUtils.isEmpty(t)) {
                t = querySceneInstService.getMainOfferInst(sceneInstId).getOfferInstId();
            }
            if (KiteStringUtils.isNotEmpty(kiteSceneInst.getCustId())) {
                List<KiteOfferInstContract> contracts = querySceneInstService
                    .listOfferInstContracts(kiteSceneInst.getCustId(), t);
                if (!KiteListUtils.isEmpty(contracts)) {
                    for (KiteOfferInstContract contract : contracts) {
                        if (!KiteStringUtils.equals(contract.getActionType().name(), ActionType.X.name())
                            && !KiteStringUtils.equals(contract.getActionType().name(), ActionType.D.name())) {
                            operateOfferInstContractRelService
                                .deleteOfferInstContractRel(sceneInstId, t, InstType.MAIN_OFFER_INST,
                                    contract.getOfferObjInstRelId());
                        }
                    }
                }
            }
            // 注意:此处添加合同跟主套餐的关系,核心能力默认关联的是当前场景的客户。所以转单获取合同信息,默认要获取场景中的客户。
            operateOfferInstContractRelService
                .addOfferInstContractRel(sceneInstId, t, InstType.MAIN_OFFER_INST, contractId, contractNo, contractName,
                    realPath, contractType,null);
        });
    }

    private String getUrl(QryStockAttachMentUrlReqDTO qryStockAttachMentUrlReq) {
        QryStockAttachMentUrlRspDTO qryStockAttachMentUrlRspDTO = SpringUtil.getBean(IAttachmentService.class)
            .getStockAttachmentUrl(qryStockAttachMentUrlReq);
        if (KiteObjectUtils.isEmpty(qryStockAttachMentUrlRspDTO)) {
            return "";
        }
        return qryStockAttachMentUrlRspDTO.getUrl();
    }

    /**
     * 解析DataRule，获取校验结果报错信息
     *
     * @param dataRuleResult
     * @return
     */
    private String parsingDataRuleMessage(DataRuleResult dataRuleResult) {
        String resultMsg = "";
        if (!KiteObjectUtils.isEmpty(dataRuleResult) && !KiteObjectUtils.isEmpty(dataRuleResult.getResultObject())) {
            return resultMsg;
        }
        DataRuleResultObj dataRuleResultObj = dataRuleResult.getResultObject();
        List<RejectPromptMessage> rejectPromptMessageList = dataRuleResultObj.getRejectPromptMessages();
        if (KiteStringUtils.isNotEmpty(dataRuleResult.getResultMsg())) {
            resultMsg = dataRuleResult.getResultMsg();
        }
        if (KiteListUtils.isNotEmpty(rejectPromptMessageList)) {
            for (RejectPromptMessage rejectPromptMessage : rejectPromptMessageList) {
                if (KiteStringUtils.isNotEmpty(rejectPromptMessage.getMessage())) {
                    resultMsg = resultMsg + ";" + rejectPromptMessage.getMessage();
                }
            }
        }
        return resultMsg;
    }
}
